<template>
    <div class="level_list">
        <el-row>
            <el-col class="zw-table-btns">
                <el-button type="primary" v-auth="'distribution_members:level_add'" @click="showDialog(1)">
                    新增等级
                </el-button>
            </el-col>
        </el-row>
        <el-table :data="Data.tableData" border>
            <el-table-column align="center" prop="levelGrade" width="100" label="等级"> </el-table-column>
            <el-table-column align="center" width="120" prop="levelName" label="等级名称"> </el-table-column>
            <el-table-column align="center" prop="upgradeRules" label="升级条件">
                <template v-slot="{ row }">
                    <div v-if="row.isDefault" class="condition">
                        <div>1、手机号注册</div>
                        <div v-for="(item, index) in row.upgradeRules" :key="item">{{ index + 2 }}、{{ item }}</div>
                    </div>
                    <div v-else class="condition">
                        <div v-for="(item, index) in row.upgradeRules" :key="item">{{ index + 1 }}、{{ item }}</div>
                    </div>
                </template>
            </el-table-column>
            <!-- 没开启邀请佣金，则仅展示推广佣金 -->
            <el-table-column align="center" prop="benefitRules" label="等级权益">
                <template v-slot="{ row }">
                    <span>推广佣金 {{ row.benefitRules.rate }}%；</span>
                    <span v-if="Data.inviteSwitch === 2"> 邀请佣金 {{ row.benefitRules.inviteRate }}% </span>
                </template>
            </el-table-column>
            <el-table-column width="140" label="操作">
                <template #default="scope">
                    <el-button
                        size="small"
                        v-auth="'distribution_members:level_edit'"
                        @click.stop="showDialog(2, scope.row)">
                        编辑
                    </el-button>
                    <el-button
                        size="small"
                        v-auth="'distribution_members:level_remove'"
                        v-show="scope.row?.isDefault !== 1"
                        @click.stop="deleteHandler(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog destroy-on-close v-model="dialog.visible" :title="dialog.title" width="50%">
            <el-form ref="dialogForm" :model="dialogFormData" :rules="rules" label-width="80px">
                <el-form-item label="等级" prop=""> {{ dialogFormData.levelGrade }} </el-form-item>
                <el-form-item label="等级名称" prop="levelName">
                    <el-input
                        :maxlength="6"
                        style="width: 180px"
                        v-model="dialogFormData.levelName"
                        placeholder="请输入"
                        autocomplete="off" />
                    <span class="form_item_tip">不超过6个字</span>
                </el-form-item>
                <!-- 新增一级时不显示 -->
                <el-form-item
                    label="升级条件"
                    v-if="!(dialogFormData.isDefault && dialog.type === 1)"
                    prop="checkListValue">
                    <div v-if="dialogFormData.isDefault">
                        <div>1、手机号注册</div>
                        <div v-for="(item, index) in dialogFormData.upgradeRules" :key="item">
                            {{ index + 1 }}、{{ item }}
                        </div>
                    </div>
                    <div v-else>
                        <el-checkbox-group @change="checkListChange" v-model="dialogFormData.checkListValue">
                            <div class="input_line">
                                <el-checkbox label="totalMoney">
                                    累计推广金额达
                                    <el-input-number
                                        :disabled="!dialogFormData.checkListValue.includes('totalMoney')"
                                        v-model="dialogFormData.totalMoney"
                                        :controls="false"
                                        :min="0.01"
                                        :max="9999999"
                                        :precision="2"></el-input-number>
                                    元
                                </el-checkbox>
                            </div>
                            <div class="input_line">
                                <el-checkbox label="totalFans">
                                    累计绑定粉丝
                                    <el-input-number
                                        :disabled="!dialogFormData.checkListValue.includes('totalFans')"
                                        v-model="dialogFormData.totalFans"
                                        :controls="false"
                                        :min="1"
                                        :max="9999999"
                                        :precision="0"></el-input-number>
                                    个
                                </el-checkbox>
                            </div>
                            <div class="">
                                <el-checkbox label="totalDistributor">
                                    累计绑定分销员
                                    <el-input-number
                                        :disabled="!dialogFormData.checkListValue.includes('totalDistributor')"
                                        v-model="dialogFormData.totalDistributor"
                                        :controls="false"
                                        :min="1"
                                        :max="9999999"
                                        :precision="0">
                                    </el-input-number>
                                    个
                                </el-checkbox>
                            </div>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                <el-form-item label="权益" prop="rateValue">
                    <div class="input_line">
                        推广佣金
                        <el-input-number
                            v-model="dialogFormData.rate"
                            :controls="false"
                            :min="0"
                            :max="99"
                            :precision="2">
                        </el-input-number>
                        %
                    </div>
                    <div v-if="Data.inviteSwitch === 2" style="width: 100%">
                        邀请佣金
                        <el-input-number
                            v-model="dialogFormData.inviteRate"
                            :controls="false"
                            :min="0"
                            :max="99"
                            :precision="2">
                        </el-input-number>
                        %
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="addComfirmHandler">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="">
import { ref, reactive, inject, onMounted, watch } from 'vue';
import { dealObjectEmptyValue, numberChinese } from '@/commons/utils.js';
import { ZwMessage } from '@/commons';
import request from '@/request';
const confirm = inject('confirm');
const dialogForm = ref(null);
const props = defineProps({
    levelList: {
        default: () => {
            return [];
        },
        type: Array
    },
    inviteSwitch: {
        type: Number
    }
});
const Data = reactive({
    // 邀请佣金开关 1-关闭 2-开启
    inviteSwitch: 1,
    totalCount: 0,
    tableData: []
});
const dialog = reactive({
    visible: false,
    type: 1,
    title: ''
});
const dialogFormData = reactive({
    levelGrade: '',
    levelName: '',
    checkListValue: [],
    totalMoney: null,
    totalFans: null,
    totalDistributor: null,
    upgradeRules: [],
    // 给个默认值去通过表单校验
    rateValue: 1,
    inviteRate: null,
    rate: null
});

// 自定义表单校验
const validateFields = ({ field }, value, callback) => {
    switch (field) {
        case 'checkListValue':
            // 等级1跳过校验
            if (dialogFormData.isDefault) {
                callback();
            }
            if (!dialogFormData.checkListValue || dialogFormData.checkListValue.length === 0) {
                callback(new Error('请至少选择一个升级条件'));
            }
            if (dialogFormData.checkListValue.find(x => !dialogFormData[x])) {
                callback(new Error('请填写选择的升级条件'));
            } else {
                callback();
            }
            break;
        case 'rateValue':
            if (dialogFormData.rate >= 100 || (dialogFormData.inviteRate >= 100 && Data.inviteSwitch === 2)) {
                callback(new Error('请输入小于100的佣金比例!'));
            }
            if (
                dialogFormData.rate !== null &&
                dialogFormData.rate > -1 &&
                ((dialogFormData.inviteRate !== null && dialogFormData.inviteRate > -1) || Data.inviteSwitch !== 2)
            ) {
                callback();
            } else {
                callback(new Error('请输入佣金比例!'));
            }
            break;
        default:
            break;
    }
};
const rules = reactive({
    levelName: [{ required: true, message: '请填写等级名称', trigger: 'blur' }],
    checkListValue: [{ required: true, validator: validateFields, trigger: 'change' }],
    rateValue: [
        { required: true, validator: validateFields, trigger: 'change' },
        { required: true, message: '请选择', trigger: 'blur' }
    ]
});

/** 监听外部传递进来的的数据变化*/
watch(
    () => props.inviteSwitch,
    () => {
        Data.inviteSwitch = props.inviteSwitch;
    }
);

const getLevelList = () => {
    Data.tableData = props.levelList;
};
const searchLevelList = async () => {
    const { data } = await request('queryDistributorLevelListServ');
    Data.tableData.length = 0;
    const list = data.list;
    Object.assign(Data.tableData, list);
};

// 取消选择置为空
const checkListChange = val => {
    const keys = ['totalMoney', 'totalFans', 'totalDistributor'];
    keys.forEach(x => {
        if (!val.includes(x)) {
            dialogFormData[x] = null;
        }
    });
};

const showDialog = (type, row) => {
    dialog.type = type;
    switch (type) {
        case 1:
            dialog.title = '新增等级';
            dialogFormData.levelId = '';
            dialogFormData.levelGrade = numberChinese(Data.tableData.length + 1) + '级';
            Data.tableData.isDefault = Number(!!Data.tableData.length);
            dialogFormData.levelName = '';
            dialogFormData.checkListValue = [];
            // 新增等级时的默认值
            dialogFormData.totalMoney = null;
            dialogFormData.totalFans = null;
            dialogFormData.totalDistributor = null;
            dialogFormData.rate = null;
            dialogFormData.inviteRate = null;
            dialog.visible = true;
            break;
        case 2:
            dialog.title = '编辑等级';
            request('queryDistributorLevelInfoServ', { id: row.id }).then(res => {
                const obj = res.data.info;
                dialogFormData.isDefault = obj.isDefault;
                dialogFormData.levelId = obj.id;
                dialogFormData.levelGrade = obj.levelGrade;
                dialogFormData.levelName = obj.levelName;
                dialogFormData.upgradeRules = obj.upgradeRules;
                dialogFormData.rate = Number(obj.benefitRules?.rate);
                dialogFormData.inviteRate = Number(obj.benefitRules?.inviteRate);
                // 升级条件回显
                dialogFormData.checkListValue = [];
                const keys = Object.keys(obj.upgradeRulesConfig);
                keys.forEach(x => {
                    if (obj.upgradeRulesConfig[x] > 0) {
                        dialogFormData.checkListValue.push(x);
                        dialogFormData[x] = Number(obj.upgradeRulesConfig[x]);
                    } else {
                        dialogFormData[x] = null;
                    }
                });
                dialog.visible = true;
            });
            break;
        default:
            break;
    }
};
// 表单提交
const addComfirmHandler = () => {
    dialogForm.value.validate(valid => {
        if (valid) {
            let para = {
                levelId: dialog.type === 2 ? dialogFormData.levelId : '',
                levelName: dialogFormData.levelName,
                applyRule: {
                    totalMoney: dialogFormData.checkListValue.includes('totalMoney') ? dialogFormData.totalMoney : '',
                    totalFans: dialogFormData.checkListValue.includes('totalFans') ? dialogFormData.totalFans : '',
                    totalDistributor: dialogFormData.checkListValue.includes('totalDistributor')
                        ? dialogFormData.totalDistributor
                        : ''
                },
                benefitRules: {
                    rate: dialogFormData.rate,
                    inviteRate: Data.inviteSwitch === 2 ? dialogFormData.inviteRate : 0
                }
            };
            const requestName = dialog.type === 1 ? 'addDistributorLevelServ' : 'editDistributorLevelServ';
            para = dealObjectEmptyValue(Object.assign(para, { applyRule: dealObjectEmptyValue(para.applyRule) }));
            request(requestName, para).then(() => {
                ZwMessage.success(`操作成功`);
                dialog.visible = false;
                searchLevelList();
            });
        }
    });
};

// 删除等级
const deleteHandler = async row => {
    try {
        if (await confirm(`请再次确认，删除？`)) {
            await request('deleteDistributorLevelServ', { id: row.id });
            ZwMessage.success(`操作成功`);
            searchLevelList();
        }
    } catch (e) {}
};

// 获取分销设置
const getSetting = async row => {
    const { data } = await request('distributionSettingsInfo', {
        tab: 1
    });
    Data.inviteSwitch = Number(data.info?.inviteSwitch);
};

onMounted(() => {
    getLevelList();
    // getSetting();
});
</script>
<style lang="scss" scoped>
.level_list {
    .condition {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
    }
    .form_item_tip {
        font-size: 14px;
        font-weight: 400;
        color: #999999;
        margin-left: 10px;
    }
    .input_line {
        margin-bottom: 12px;
    }
    .el-table {
        box-shadow: none;
        :deep(.el-table__empty-block) {
            border-bottom: 1px solid #eaeaea;
        }
    }
}
</style>
